package com.plugin.manage.controller;

import com.plugin.manage.common.PageResult;
import com.plugin.manage.common.RespObj;
import com.plugin.manage.service.ICheckoutService;
import com.plugin.manage.pojo.vo.ElderCheckoutApplymentVO;
import com.plugin.manage.pojo.vo.ElderCheckoutDynamicVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退住管理控制器
 *
 * @author mark
 * @date 2025-08-04
 */
@Tag(name = "退住管理", description = "退住相关接口")
@RestController
@RequestMapping("/checkout")
public class CheckoutController {

    private static final Logger log = LoggerFactory.getLogger(CheckoutController.class);
    
    @Autowired
    private ICheckoutService checkoutService;

    /**
     * 获取总退住记录数量（不筛选approval_status）
     *
     * @return 总退住记录数量
     */
    @Operation(summary = "总退住记录数量", description = "统计elder_check_out表中所有记录数（不筛选approval_status）")
    @GetMapping("/totalCount")
    public RespObj<?> getTotalCheckoutCount() {
        log.info("开始获取总退住记录数量");
        Long count = checkoutService.getTotalCheckoutCount();
        log.info("总退住记录数量：{}", count);
        return new RespObj<Long>().success(count);
    }

    /**
     * 获取approval_status=1的退住记录数量
     *
     * @return approval_status=1的退住记录数量
     */
    @Operation(summary = "退住状态1记录数量", description = "统计elder_check_out表中approval_status=1的记录数")
    @GetMapping("/applyCount")
    public RespObj<?> getStatus1CheckoutCount() {
        log.info("开始获取approval_status=1的退住记录数量");
        Long count = checkoutService.getStatus1CheckoutCount();
        log.info("approval_status=1的退住记录数量：{}", count);
        return new RespObj<Long>().success(count);
    }
    
    /**
     * 获取approval_status=2的退住记录数量
     *
     * @return approval_status=2的退住记录数量
     */
    @Operation(summary = "退住状态2记录数量", description = "统计elder_check_out表中approval_status=2的记录数")
    @GetMapping("/toAuditCount")
    public RespObj<?> getStatus2CheckoutCount() {
        log.info("开始获取approval_status=2的退住记录数量");
        Long count = checkoutService.getStatus2CheckoutCount();
        log.info("approval_status=2的退住记录数量：{}", count);
        return new RespObj<Long>().success(count);
    }
    
    /**
     * 获取approval_status=3的退住记录数量
     *
     * @return approval_status=3的退住记录数量
     */
    @Operation(summary = "退住状态3记录数量", description = "统计elder_check_out表中approval_status=3的记录数")
    @GetMapping("/toChargeCount")
    public RespObj<?> getStatus3CheckoutCount() {
        log.info("开始获取approval_status=3的退住记录数量");
        Long count = checkoutService.getStatus3CheckoutCount();
        log.info("approval_status=3的退住记录数量：{}", count);
        return new RespObj<Long>().success(count);
    }
    
    /**
     * 获取approval_status=4的退住记录数量
     *
     * @return approval_status=4的退住记录数量
     */
    @Operation(summary = "退住状态4记录数量", description = "统计elder_check_out表中approval_status=4的记录数")
    @GetMapping("/completeCount")
    public RespObj<?> getStatus4CheckoutCount() {
        log.info("开始获取approval_status=4的退住记录数量");
        Long count = checkoutService.getStatus4CheckoutCount();
        log.info("approval_status=4的退住记录数量：{}", count);
        return new RespObj<Long>().success(count);
    }

    /**
     * 获取所有审批状态的退住记录数量
     *
     * @return 包含所有审批状态数量的Map
     */
    @Operation(summary = "所有退住状态记录数量", description = "使用CASE WHEN一次性统计所有approval_status的记录数量")
    @GetMapping("/process")
    public RespObj<?> getAllStatusCheckoutCounts() {
        log.info("开始获取所有审批状态的退住记录数量");
        Map<String, Long> statusCounts = checkoutService.getAllStatusCheckoutCounts();
        
        // 重命名Map中的键以匹配其他接口的命名
        Map<String, Long> renamedCounts = new HashMap<>();
        renamedCounts.put("applyCount", statusCounts.get("status1Count"));
        renamedCounts.put("toAuditCount", statusCounts.get("status2Count"));
        renamedCounts.put("toChargeCount", statusCounts.get("status3Count"));
        renamedCounts.put("completeCount", statusCounts.get("status4Count"));
        
        log.info("所有审批状态的退住记录数量：{}", renamedCounts);
        return new RespObj<Map<String, Long>>().success(renamedCounts);
    }

    /**
     * 查询长者姓名和退住状态
     *
     * @return 长者姓名和退住状态列表
     */
    @Operation(summary = "查询长者姓名和退住状态", description = "查询elder_info.realname和elder_check_out.approval_status")
    @GetMapping("/dynamic")
    public RespObj<?> queryElderNameAndStatus() {
        log.info("开始查询长者姓名和退住状态");
        List<ElderCheckoutDynamicVO> result = checkoutService.queryElderNameAndStatus();
        log.info("查询到{}条长者姓名和退住状态记录", result.size());
        return new RespObj<List<ElderCheckoutDynamicVO>>().success(result);
    }
    
    /**
     * 查询退住申请详情
     *
     * @param realname 长者姓名（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @param sex 性别（可选）
     * @param roomNumber 房间号（可选）
     * @return 退住申请详情列表
     */
    @Operation(summary = "查询退住申请详情", description = "查询退住申请详情，包含长者基本信息和退住信息")
    @GetMapping("/applyment")
    public RespObj<?> queryCheckoutApplyments(
            @Parameter(description = "长者姓名") @RequestParam(required = false) String realname,
            @Parameter(description = "开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @Parameter(description = "性别") @RequestParam(required = false) Integer sex,
            @Parameter(description = "房间号") @RequestParam(required = false) String roomNumber,
            @Parameter(description = "当前页", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size) {
        log.info("开始查询退住申请详情，条件：realname={}, startTime={}, endTime={}, sex={}, roomNumber={}",
                realname, startTime, endTime, sex, roomNumber);
        PageResult<ElderCheckoutApplymentVO> result = checkoutService.queryCheckoutApplyments(current,size,
                realname, startTime, endTime, sex, roomNumber);
        return new RespObj<PageResult<ElderCheckoutApplymentVO>>().success(result);
    }
}
